package cn.wenhaha.common.utils;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 获取对象的内存地址
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-12-03 18:41
 */
public class AddressUtil {

    private static Unsafe unsafe;

    static
    {
        try
        {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe)field.get(null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static long addressOf(Object o)
    {
        Object[] array = new Object[] {o};

        long baseOffset = unsafe.arrayBaseOffset(Object[].class);
        int addressSize = unsafe.addressSize();
        long objectAddress;
        switch (addressSize)
        {
            case 4:
                objectAddress = unsafe.getInt(array, baseOffset);
                break;
            case 8:
                objectAddress = unsafe.getLong(array, baseOffset);
                break;
            default:
                throw new Error("不支持的地址长度 : " + addressSize);
        }

        return(objectAddress);
    }


    public static void main(String... args)
            throws Exception
    {
        Object mine = "Hi there".toCharArray();
        long address = addressOf(mine);
        System.out.println("Addess: " + address);



    }


}
